<script setup>
import { ref, computed, watch } from 'vue'
import { Plus, UploadFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios';
// API基础URL（从环境变量获取，自动适配环境）
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
// 合同编辑对话框
const dialogVisible = ref(false)
const templateDialogVisible = ref(false)
const previewDialogVisible = ref(false)
const formRef = ref(null)
const loading = ref(false)

// 合同模板数据
const contractTemplates = ref([
  {
    id: 1,
    title: '服务合同模板',
    type: '服务合同',
    image: new URL('@/assets/template/service.png', import.meta.url).href,
    downloadCount: 756,
    parties: {
      partyA: '委托方',
      partyB: '服务方'
    },
    content: [
      {
        title: '一、服务内容',
        items: [
          '1. 服务项目：________________',
          '2. 服务范围：________________',
          '3. 服务标准：________________',
          '4. 服务期限：________________'
        ]
      },
      {
        title: '二、服务费用',
        items: [
          '1. 服务费用总额：________________',
          '2. 支付方式：________________',
          '3. 支付时间：________________',
          '4. 发票要求：________________'
        ]
      }
    ]
  },
  {
    id: 2,
    title: '房屋租赁合同模板',
    type: '租赁合同',
    image: new URL('@/assets/template/rental.png',import.meta.url).href,
    downloadCount: 1420,
    parties: {
      partyA: '出租方',
      partyB: '承租方'
    },
    content: [
      {
        title: '一、租赁信息',
        items: [
          '1. 房屋地址：________________',
          '2. 租赁面积：________________',
          '3. 租赁期限：________________',
          '4. 租金标准：________________'
        ]
      }
    ]
  }
])
// 选中的模板
const selectedTemplate = ref(null)
const previewTemplateData = ref(null)
// 合同状态选项
const contractStatusOptions = ref([
  { label: '待审批', value: '待审批' },
  { label: '已签署', value: '已签署' },
  { label: '已拒绝', value: '已拒绝' },
  { label: '生效中', value: '生效中' },
  { label: '即将到期', value: '即将到期' },
  { label: '已终止', value: '已终止' },
  { label: '已逾期', value: '已逾期' }
])

// 合同类型选项
const contractTypeOptions = ref([
  { label: '租赁合同', value: '租赁合同' },
  { label: '服务合同', value: '服务合同' },
  { label: '合作协议', value: '合作协议' },
  { label: '采购合同', value: '采购合同' }
])

// 表单初始数据
const defaultForm = {
  contractNumber: '',
  title: '',
  applicant: '',
  startDate: '',
  companyName: '',
  companyAddress: '',
  endDate: '',
  changeReason: '',
  contractType: '租赁合同',
  contractStatus: '待审批',
  contractTemplate: '' // 选中的合同模板
}

// 表单数据
const form = ref({ ...defaultForm })

// 保存原始数据用于比较变更
const originalData = ref({})

// 表单验证规则
const formRules = {
  startDate: [{ required: true, message: '请选择生效日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
  companyName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
  companyAddress: [{ required: true, message: '请输入企业地址', trigger: 'blur' }],
  title: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
  applicant: [{ required: true, message: '请输入申请人', trigger: 'blur' }],
  contractType: [{ required: true, message: '请选择合同类型', trigger: 'change' }],
  contractStatus: [{ required: true, message: '请选择合同状态', trigger: 'change' }],
  contractTemplate: [{ required: true, message: '请选择合同模板', trigger: 'change' }],
  changeReason: [{ 
    required: false, 
    message: '变更合同必须填写原因', 
    trigger: 'blur',
    validator: (rule, value, callback) => {
      if (form.value.id && !value) {
        callback(new Error('变更合同必须填写变更原因'))
      } else {
        callback()
      }
    }
  }],
  attachments:[{
    required:true,
    validator:(rule,value,callback)=>{
      if(!issueForm.value.attachments || issueForm.value.length===0){
        callback(new Error('请上传合同附件'))
      }else{
        callback()
      }
    },
    trigger:'change'
  }]
}

// 打开对话框
const open = (row = {}) => {
  if (row.id) {
    // 编辑模式：填充表单
    form.value = {
      id: row.id,
      contractNumber: row.contractNumber || '',
      title: row.title || '',
      applicant: row.applicant || '',
      startDate: row.startDate || '',
      companyName: row.companyName || '',
      companyAddress: row.companyAddress || '',
      endDate: row.endDate || '',
      contractType: row.contractType || '租赁合同',
      contractStatus: row.contractStatus || '待审批',
      changeReason: row.changeReason || ''
    }
    // 保存原始数据用于变更检测
    originalData.value = { ...form.value }
    // 恢复附件列表
    issueForm.value.attachments = row.attachments || []
  } else {
    // 新增模式：重置表单
    resetForm()
  }
  dialogVisible.value = true
}

// 显示模板选择对话框
const showTemplateDialog = () => {
  templateDialogVisible.value = true
  selectedTemplate.value = null
}

// 选择模板
const selectTemplate = (template) => {
  selectedTemplate.value = template
}

// 预览模板
const previewTemplate = (template) => {
  previewTemplateData.value = template
  previewDialogVisible.value = true
}

// 使用预览的模板
const usePreviewTemplate = () => {
  if (previewTemplateData.value) {
    form.value.contractTemplate = previewTemplateData.value.title
    previewDialogVisible.value = false
    templateDialogVisible.value = false
    ElMessage.success(`已选择模板: ${previewTemplateData.value.title}`)
  }
}

// 确认模板选择
const confirmTemplateSelection = () => {
  if (selectedTemplate.value) {
    form.value.contractTemplate = selectedTemplate.value.title
    templateDialogVisible.value = false
    ElMessage.success(`已选择模板: ${selectedTemplate.value.title}`)
  }
}


// 生成合同编号
const generateContractNumber = () => {
  return 'CT' + Date.now().toString().slice(-8)
}

// 重置表单
const resetForm = () => {
  form.value = { 
    ...defaultForm, 
    contractNumber: generateContractNumber() 
  }
  originalData.value = {}
  issueForm.value.attachments = []
}

// 关闭对话框
const handleClose = (done) => {
  done()
}

const emit = defineEmits(['article-added'])


// 记录合同变更历史
const recordContractChange = async (originalData,contractData, changeReason) => {
  try {
    const api = axios.create({
      baseURL: import.meta.env.VITE_API_BASE_URL,
      timeout: 5000
    })
    
    // 构建变更历史记录数据
    const changeHistoryData = {
      contractId: contractData.id,
      contractNumber: contractData.contractNumber,
      contractName: contractData.title,
      actionType: 'update',
      changeReason: changeReason || '合同信息更新',
      previousData: originalData || {},
      currentData: contractData,
      changedBy: 'system' 
    }
    
    console.log('提交变更历史数据:', changeHistoryData)
    
    // 调用添加变更记录接口
    const response = await api.post(`${API_BASE_URL}/api/contract-change-history`, changeHistoryData)
    
    if (response.data && response.data.success) {
      console.log('合同变更记录保存成功，记录ID:', response.data.data)
    } else {
      console.warn('合同变更记录保存失败:', response.data?.message)
    }
  } catch (error) {
    console.error('记录合同变更历史失败:', error)
  }
}

// 提交表单
const submitForm = async () => {
  try {
    //先手动验证附件
    if(!issueForm.value.attachments||issueForm.value.attachments.length === 0){
      ElMessage.error('请先上传合同附件')
      return
    }
    await formRef.value.validate()
    loading.value = true
    // 在提交前保存原始数据副本
    const originalDataBeforeSubmit = form.value.id ? { ...originalData.value } : null
    // 处理附件数据
    const attachments = issueForm.value.attachments.map(file => ({
      name: file.name,
      size: file.size,
      url: file.url || '',
      uploadDate: file.uploadDate || new Date().toISOString().split('T')[0]
    }))
    
    // 构建请求数据
    const requestData = {
      contractNumber: form.value.contractNumber,
      title: form.value.title,
      applicant: form.value.applicant,
      companyName: form.value.companyName,
      companyAddress: form.value.companyAddress,
      contractType: form.value.contractType,
      startDate: form.value.startDate,
      endDate: form.value.endDate,
      contractStatus: form.value.contractStatus,
      attachments: attachments,
      ...(form.value.id && { changeReason: form.value.changeReason })
    }
    
    let url = `${API_BASE_URL}/api/contracts`
    let method = 'POST'
    
    if (form.value.id) {
      // 编辑模式
      url = `${API_BASE_URL}/api/contracts/${form.value.id}`
      method = 'PUT'
      requestData.id = form.value.id
    }
    
    const response = await fetch(url, {
      method: method,
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestData)
    })
    
    if (response.ok) {
      const data = await response.json()
      if (data.success) {
        // 如果是编辑模式，记录变更历史
        if (form.value.id) {
          await recordContractChange(originalDataBeforeSubmit,data.data,form.value.changeReason)
        }
        ElMessage.success(form.value.id ? '合同更新成功' : '合同创建成功')
        emit('article-added', data.data)
        dialogVisible.value = false
        resetForm()
      } else {
        ElMessage.error(data.message || '操作失败')
      }
    } else {
      const errorData = await response.json()
      ElMessage.error(errorData.message || '网络请求失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('请填写完整的合同信息')
  } finally {
    loading.value = false
  }
}

// 修改对话框标题
const dialogTitle = computed(() => {
  return form.value.id ? '合同变更' : '合同录入'
})

// 附件上传相关
const issueForm = ref({
  attachments: []
})

const handleExceed = () => {
  ElMessage.warning('最多只能上传5个文件')
}

const handleFileChange = (file, fileList) => {
  issueForm.value.attachments = fileList.map(f => ({
    name: f.name,
    size: f.size,
    url: f.url || URL.createObjectURL(f.raw),
    uploadDate: new Date().toISOString().split('T')[0]
  }))
  //手动触发附件验证
  if(formRef.value){
    formRef.value.validateField('attachments')
  }
}

const handleFileRemove = (file, fileList) => {
  issueForm.value.attachments = fileList
  //手动触发附件验证
  if(formRef.value){
    formRef.value.validateField('attachments')
  }
}

defineExpose({
  open
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="800px"
    :before-close="handleClose"
  >
    <el-form ref="formRef" :model="form" label-width="120px" :rules="formRules" label-position="right">
      <el-row :gutter="40">
        <el-col :span="12">
          <!-- 合同编号 -->
          <el-form-item label="合同编号：">
            <el-input v-model="form.contractNumber" disabled />
          </el-form-item>
          
          <el-form-item label="合同名称：" prop="title">
            <el-input v-model="form.title" placeholder="请输入合同名称" />
          </el-form-item>

          <el-form-item label="申请人：" prop="applicant">
            <el-input v-model="form.applicant" placeholder="请输入申请人姓名" />
          </el-form-item>

          <el-form-item label="合同类型：" prop="contractType">
            <el-select v-model="form.contractType" placeholder="请选择合同类型" style="width: 100%">
              <el-option
                v-for="type in contractTypeOptions"
                :key="type.value"
                :label="type.label"
                :value="type.value"
              />
            </el-select>
          </el-form-item>

           <el-form-item label="合同模板：" prop="contractTemplate" required>
            <div class="template-selector">
              <el-input 
                v-model="form.contractTemplate" 
                placeholder="请选择合同模板" 
                readonly
                style="width: calc(100% - 40px)"
              />
              <el-button 
                type="primary" 
                circle 
                @click="showTemplateDialog"
                style="margin-left: 8px;"
              >
                <el-icon><Plus /></el-icon>
              </el-button>
            </div>
          </el-form-item>

          <el-form-item label="合同状态：" prop="contractStatus">
            <el-select v-model="form.contractStatus" placeholder="请选择合同状态" style="width: 100%">
              <el-option
                v-for="status in contractStatusOptions"
                :key="status.value"
                :label="status.label"
                :value="status.value"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="合同生效时间：" prop="startDate">
            <el-date-picker
              v-model="form.startDate"
              type="date"
              placeholder="选择日期"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>

        </el-col>
        
        <el-col :span="12">                 
          <el-form-item label="企业名称：" prop="companyName">
            <el-input v-model="form.companyName" placeholder="请输入企业名称" />
          </el-form-item>
          
          <el-form-item label="企业地址：" prop="companyAddress">
            <el-input 
              v-model="form.companyAddress" 
              placeholder="请输入企业地址" 
              type="textarea"
              :rows="2"
            />
          </el-form-item>
          
          <el-form-item label="合同到期时间：" prop="endDate">
            <el-date-picker
              v-model="form.endDate"
              type="date"
              placeholder="选择日期"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
          
          <el-form-item 
            label="合同变更原因：" 
            prop="changeReason"
            v-if="form.id"  
            required
          >
            <el-input
              v-model="form.changeReason"
              type="textarea"
              :rows="3"
              placeholder="请输入合同变更原因"
              clearable
            />
          </el-form-item>

          <el-form-item
           label="附件上传"
           prop="attachments"
           required
           >
            <el-upload
              action="#"
              multiple
              :limit="5"
              :file-list="issueForm.attachments"
              :auto-upload="false"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              drag
              :on-exceed="handleExceed"
              style="width: 100%"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                拖拽文件到此处或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  支持上传文档、图片等附件，单个文件不超过10MB
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false" :disabled="loading">取消</el-button>
        <el-button 
          type="primary" 
          @click="submitForm"
          :loading="loading"
        >
          {{ form.id ? '保存变更' : '确认新增' }}
        </el-button>
      </span>
    </template>
  </el-dialog>

    <!-- 合同模板选择对话框 -->
  <el-dialog
    v-model="templateDialogVisible"
    title="选择合同模板"
    width="900px"
    class="template-select-dialog"
  >
    <div class="template-grid">
      <div 
        v-for="template in contractTemplates" 
        :key="template.id"
        class="template-card"
        :class="{ 'selected': selectedTemplate?.id === template.id }"
        @click="selectTemplate(template)"
      >
        <div class="template-image">
          <img :src="template.image" :alt="template.title" />
          <div class="template-overlay">
            <el-button type="primary" size="small" @click.stop="previewTemplate(template)">
              预览
            </el-button>
          </div>
        </div>
        <div class="template-info">
          <h4 class="template-title">{{ template.title }}</h4>
          <div class="template-meta">
            <span class="download-count">
            </span>
            <span class="template-type">{{ template.type }}</span>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="templateDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmTemplateSelection"
          :disabled="!selectedTemplate"
        >
          确认选择
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 模板预览对话框 -->
  <el-dialog
    v-model="previewDialogVisible"
    :title="previewTemplateData?.title"
    width="800px"
    class="template-preview-dialog"
  >
    <div class="template-detail-content">
      <div class="template-preview">
        <div class="preview-header">
          <h3>{{ previewTemplateData?.title }}</h3>
          <el-button type="primary" @click="usePreviewTemplate">
            <el-icon><DocumentAdd /></el-icon>
            使用此模板
          </el-button>
        </div>
        <div class="word-content">
          <div class="word-document">
            <!-- 合同标题 -->
            <div class="document-title">
              <h2>{{ previewTemplateData?.title }}</h2>
            </div>
            
            <!-- 合同双方 -->
            <div class="document-parties">
              <p>甲方（{{ previewTemplateData?.parties?.partyA }}）：________________</p>
              <p>乙方（{{ previewTemplateData?.parties?.partyB }}）：________________</p>
            </div>

            <!-- 合同内容 -->
            <div 
              v-for="(section, index) in previewTemplateData?.content" 
              :key="index"
              class="document-section"
            >
              <h4>{{ section.title }}</h4>
              <div 
                v-for="(item, itemIndex) in section.items" 
                :key="itemIndex"
                class="document-item"
              >
                {{ item }}
              </div>
            </div>

            <!-- 签名区域 -->
            <div class="document-signature">
              <div class="signature-party">
                <p>甲方（盖章）：</p>
                <p>代表签字：________________</p>
                <p>日期：________________</p>
              </div>
              <div class="signature-party">
                <p>乙方（盖章）：</p>
                <p>代表签字：________________</p>
                <p>日期：________________</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<style lang="scss" scoped>
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}

.el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 7px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  gap: 10px;
}

/* 模板选择对话框样式 */
.template-select-dialog {
  .template-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 20px;
    max-height: 500px;
    overflow-y: auto;
    padding: 10px;
  }

  .template-card {
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    cursor: pointer;
    transition: all 0.3s ease;
    border: 2px solid transparent;

    &.selected {
      border-color: #409eff;
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
    }
  }

  .template-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }

  .template-image {
    position: relative;
    height: 150px;
    overflow: hidden;
  }

  .template-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .template-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
  }

  .template-card:hover .template-overlay {
    opacity: 1;
  }

  .template-info {
    padding: 12px;
  }

  .template-info .template-title {
    font-size: 14px;
    font-weight: 600;
    margin: 0 0 8px 0;
    color: #303133;
    line-height: 1.4;
  }

  .template-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 12px;
    color: #909399;
  }

  .download-count {
    display: flex;
    align-items: center;
    gap: 4px;
  }

  .template-type {
    background: #f0f2f5;
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 11px;
  }
}

/* 模板预览对话框样式 */
.template-preview-dialog {
  .template-detail-content {
    max-height: 70vh;
    overflow-y: auto;
  }
  
  .preview-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
  }
  
  .word-content {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 4px;
  }
  
  .word-document {
    background: white;
    padding: 30px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    font-family: 'SimSun', serif;
    line-height: 1.6;
  }
  
  .document-title {
    text-align: center;
    margin-bottom: 30px;
    border-bottom: 2px solid #409eff;
    padding-bottom: 15px;
  }
  
  .document-parties {
    margin-bottom: 25px;
  }
  
  .document-section {
    margin-bottom: 20px;
  }
  
  .document-section h4 {
    margin-bottom: 10px;
    color: #333;
    border-left: 3px solid #409eff;
    padding-left: 10px;
  }
  
  .document-item {
    margin-bottom: 5px;
  }
  
  .document-signature {
    display: flex;
    justify-content: space-between;
    margin-top: 50px;
  }
  
  .signature-party {
    text-align: left;
  }
  
  .signature-party p {
    margin-bottom: 10px;
  }
}

@media (max-width: 768px) {
  .template-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 15px;
  }
  
  .document-signature {
    flex-direction: column;
    gap: 20px;
  }
}
</style>